﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using EnCor.Config;
using EnCor.ObjectBuilder;
using System.Xml;

namespace EnCor.Security
{
    public class IdentityMapperConfigCollection : PolymorphicConfigurationElementCollection<IdentityMapperConfig>
    {
        protected override Type RetrieveConfigurationElementType(XmlReader reader)
        {
            Type configurationElementType = null;
            Type configType = null;

            if (reader.AttributeCount > 0)
            {
                // expect the first attribute to be the name
                for (bool go = reader.MoveToFirstAttribute(); go; go = reader.MoveToNextAttribute())
                {
                    if (Constants.Config_Type.Equals(reader.Name))
                    {
                        configurationElementType = Type.GetType(reader.Value);
                        if (configurationElementType == null)
                        {
                            throw new ConfigurationErrorsException();
                        }

                        configurationElementType.GetCustomAttributes(typeof(AssembleConfigAttribute), false);

                        break;
                    }
                }

                if (configurationElementType == null)
                {
                    throw new ConfigurationErrorsException();
                }
                configType = GetConfigType(configurationElementType);

                // cover the traces
                reader.MoveToElement();
            }

            return configType;
        }

        private Type GetConfigType(Type actualType)
        {
            AssembleConfigAttribute attribute = Attribute.GetCustomAttribute(actualType, typeof(AssembleConfigAttribute)) as AssembleConfigAttribute;
            if (attribute == null)
            {
                return null;
            }
            return attribute.ConfigType;
        }
    }
}
